

package com.wzl.security;

import com.wzl.constant.CommonConstant;
import com.wzl.entity.SysLog;
import com.wzl.service.SysLogService;
import com.wzl.util.DateUtil;
import com.wzl.util.Res;
import com.wzl.util.ResUtil;
import com.wzl.util.SysLogUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author wzl
 * @date 2020-03-23 1:47 下午
 * @description 自定义登录成功后的处理
 */

@Slf4j
@Component
public class CommonLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {


    @Value("${spring.security.loginType}")
    private String loginType;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysLogService sysLogService;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String username = authentication.getName();
        log.info("=== 用户【{}】在 {} 登录了系统 ===", username, DateUtil.nowString());

        if (loginType.equalsIgnoreCase(CommonConstant.LOGIN_TYPE_JSON)) {
            // 记录日志
            addLog();
            // 生成token
            CommonUser commonUser = (CommonUser) authentication.getPrincipal();
            String token = tokenService.createToken(commonUser);
            ResUtil.jsonResult(response, Res.success(0, "登录成功", token));
        } else {
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }

    /**
     * 记录日志
     */
    private void addLog() {
        SysLog sysLog = SysLogUtil.getSysLog();
        sysLog.setTitle("【" + SysLogUtil.getUserName() + "】登录");
        sysLog.setType("1");
        sysLogService.save(sysLog);
    }
}
